# -*- coding: utf-8 -*-
# !/usr/bin/env python
from rest_framework.views import APIView

from components.kubernetes.api_config_file_text import api_config_file_text
from utils.K8S import K8sApi
from utils.views import Result, ReturnClass

class Service(APIView):
    def get(self, request):
        data = request.query_params
        kubernetes_cluster_id = data['kubernetes_cluster_id']
        name = data['name']
        namespace = data['namespace']
        label_selector = data.get('label_selector')

        label_selector_str = None
        if label_selector:
            label_selector_dict = eval(label_selector)
            for key in label_selector_dict:
                label_selector_str = "%s=%s," %(key, label_selector_dict[key])
            label_selector_str = label_selector_str[:-1]

        # 获取 配置的文件，连接api服务器
        kubernetes_cluster_sign_kubeconfig = api_config_file_text(kubernetes_cluster_id)
        if not ReturnClass.if_ok(kubernetes_cluster_sign_kubeconfig):
            return Result.fail_response(msg=ReturnClass.get_value(kubernetes_cluster_sign_kubeconfig))
        k8s_api = K8sApi(ReturnClass.get_value(kubernetes_cluster_sign_kubeconfig))

        return_data = {}
        try:
            # return_data = k8s_api.read_namespaced_service(name, namespace)
            return_data['pod_data'] = k8s_api.get_namespaced_pod(namespace, label_selector=label_selector_str)
            return_data['deployment_data'] = k8s_api.get_namespaced_deployment(namespace, label_selector=label_selector_str)
            return_data['statefulset_data'] = k8s_api.get_namespaced_stateful_set(namespace, label_selector=label_selector_str)
        except Exception as e:
            return Result.fail_response(msg=str(e))

        return Result.success_response(data=return_data, msg='查询服务信息成功')